import { z } from "zod"; import { guarded, json, body } from "@/lib/api"; import { getConversation, getActiveMessages, getAllMessages, updateConversation, deleteConversation } from "@/lib/chat/store"; import { sql } from "@/lib/db"; export const GET = guarded<{ id: string }>(async (req, { params }) => { const conv = await getConversation(params.id); if (!conv) return json({ error: "Introuvable" }, { status: 404 }); const all = req.nextUrl.searchParams.get("all") === "1"; const messages = all ? await getAllMessages(params.id) : await getActiveMessages(params.id); // sibling counts for branch navigation const sib = await sql<{ parent_id: string | null; role: string; n: number }[]>`SELECT parent_id, role, count(*)::int AS n FROM messages WHERE conversation_id = ${params.id} GROUP BY parent_id, role HAVING count(*) > 1`; const attachments = await sql`SELECT id, filename, mime, size_bytes, kind, page_count, message_id, created_at FROM attachments WHERE conversation_id = ${params.id} ORDER BY created_at`; const artifacts = await sql`SELECT id, root_id, version, type, language, title, saved, message_id, created_at FROM artifacts WHERE conversation_id = ${params.id} ORDER BY created_at`; return json({ conversation: conv, messages, siblings: sib, attachments, artifacts }); }); export const PATCH = guarded<{ id: string }>(async (req, { params }) => { const b = await body(req, z.object({ title: z.string().min(1).max(200).optional(), projectId: z.string().nullable().optional(), modelId: z.string().optional(), pinned: z.boolean().optional(), archived: z.boolean().optional(), settings: z.record(z.string(), z.unknown()).optional() })); await updateConversation(params.id, { title: b.title, project_id: b.projectId, model_id: b.modelId, pinned: b.pinned, archived: b.archived, settings: b.settings }); return json({ conversation: await getConversation(params.id) }); }); export const DELETE = guarded<{ id: string }>(async (_req, { params }) => { await deleteConversation(params.id); return json({ ok: true }); });